import {INIT_USER_INFO, INIT_USER_INFO_SAGA, REGAIN_USER, USER_SIGN_SAGA} from '@/store/common/user/type';
import {put, select, takeEvery} from 'redux-saga/effects';
import Http from '@/util/http';
import {Api, errorMsg, load, successMsg} from '@/util/global';
import EventBus from '@/util/EventBus';
import {toBase64} from '@/util/CodeUtils';
import {regainUserInfo} from '@/api/SysUserInfo';

const effects = {
    *login() {
        yield load(true);
        const user = yield select(state => state.toJS().login);
        if (!user.userName || !user.password) {
            errorMsg('账号或密码不能为空');
            yield load(false);
            return;
        }
        const ajax = yield Http.post(Api.LoginApi, {
            userName: user.userName,
            password: user.password,
            loginType: 'PASSWORD'
        });
        if (ajax.data && ajax.success) {
            yield put({ type: INIT_USER_INFO, value: ajax.data });
            sessionStorage.setItem('just-game-obj', toBase64(ajax.data));
            sessionStorage.setItem('token', ajax.data.token);
            yield load(false);
            EventBus.emit('login', true);
            successMsg(`${ajax.data.userName}，欢迎登录！`);
        } else {
            EventBus.emit('login', false);
        }
        yield load(false);
    },
    *sign() {
        const user = yield select(state => state.toJS().login.signForm);
        const ajax = yield Http.post(Api.SignUpApi, user);
        if (ajax.success === true) {
            successMsg('恭喜您！注册成功。');
            EventBus.emit('sign', true);
        }
    },
    *regainUserInfo() {
        const ajax = yield regainUserInfo();
        if (ajax.data && ajax.success) {
            yield put({ type: INIT_USER_INFO, value: ajax.data });
            sessionStorage.setItem('token', ajax.data.token);
        }
    }
};

export default function* User() {
    yield takeEvery(INIT_USER_INFO_SAGA, effects.login);
    yield takeEvery(USER_SIGN_SAGA, effects.sign);
    yield takeEvery(REGAIN_USER, effects.regainUserInfo);
}